package com.tuomaxu.service.impl;

import com.tuomaxu.dao.CodeDao;
import com.tuomaxu.pojo.AuthCode;
import com.tuomaxu.service.AuthCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Optional;


@Service
public class AuthCodeServiceImpl implements AuthCodeService {

    @Autowired
    private CodeDao codeDao;

    @Override
    public boolean addCode(AuthCode code) {
        try {
            Date now = new Date();
            code.setCreatetime(now);
            //code有效期10分钟
            code.setExpiretime(new Date(now.getTime()+600000));
            codeDao.save(code);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public Integer validateCode(AuthCode code) {
        Example<AuthCode> exa = Example.of(code);
        Date now = new Date();
        Optional<AuthCode> one = codeDao.findOne(exa);
        try {
            AuthCode authCode = one.get();
            Date expiretime = authCode.getExpiretime();
            long m = expiretime.getTime() - now.getTime();
            if(m < 0){
                return 2;
            }
            return 0;

        }catch (Exception e){
            return 1;
        }
    }
}
